package top.ywlog.permission.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ywlog.permission.common.RequestHolder;
import top.ywlog.permission.common.request.AclModuleParam;
import top.ywlog.permission.dao.SysAclModuleMapper;
import top.ywlog.permission.exception.ParamException;
import top.ywlog.permission.model.SysAclModule;
import top.ywlog.permission.util.IpUtils;
import top.ywlog.permission.util.LevelUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: Durian
 * @date: 2020/10/22 21:00
 * @description:
 */
@Slf4j
@Service
public class SysAclModuleService
{
    @Resource
    private SysAclModuleMapper sysAclModuleMapper;

    @Transactional
    public void save(AclModuleParam param)
    {
        if (checkExist(param.getParentId(), param.getName(), param.getId()))
        {
            throw new ParamException("同一层级下存在相同名称的权限模块");
        }
        SysAclModule aclModule = SysAclModule.builder().name(param.getName()).parentId(param.getParentId()).seq(param.getSeq())
                .status(param.getStatus()).remark(param.getRemark()).build();
        aclModule.setLevel(LevelUtils.calculateLevel(getLevel(param.getParentId()), param.getParentId()));
        aclModule.setOperator(RequestHolder.getCurrentUser().getUsername());
        aclModule.setOperateIp(IpUtils.getRemoteIp(RequestHolder.getCurrentRequest()));
        aclModule.setOperateTime(LocalDateTime.now());
        sysAclModuleMapper.insertSelective(aclModule);
    }

    @Transactional
    public void update(AclModuleParam param)
    {
        if (checkExist(param.getParentId(), param.getName(), param.getId()))
        {
            throw new ParamException("同一层级下存在相同名称的权限模块");
        }
        SysAclModule before = sysAclModuleMapper.selectByPrimaryKey(param.getId());
        if (before == null)
        {
            log.error("待更新的权限模块不存在，无法更新 aclModuleId:{}", param.getId());
            throw new ParamException("待更新的权限模块不存在，无法更新");
        }
        SysAclModule after = SysAclModule.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId()).seq(param.getSeq())
                .status(param.getStatus()).remark(param.getRemark()).build();
        after.setLevel(LevelUtils.calculateLevel(getLevel(param.getParentId()), param.getParentId()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtils.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(LocalDateTime.now());

        updateWithChild(before, after);
    }

    public void delete(Integer aclModuleId)
    {
        SysAclModule aclModule = sysAclModuleMapper.selectByPrimaryKey(aclModuleId);
        if (aclModule == null)
        {
            throw new ParamException("待删除的权限模块不存在，无法删除");
        }
        if (sysAclModuleMapper.countByParentId(aclModule.getId()) > 0)
        {
            throw new ParamException("当前模块下面有子模块，无法删除");
        }
        /*if (sysAclMapper.countByAclModuleId(aclModule.getId()) > 0)
        {
            throw new ParamException("当前模块下面有用户，无法删除");
        }*/
        sysAclModuleMapper.deleteByPrimaryKey(aclModuleId);
    }

    private void updateWithChild(SysAclModule before, SysAclModule after)
    {
        String newLevel = after.getLevel();
        String oldLevel = before.getLevel();
        if (!after.getLevel().equals(before.getLevel()))
        {
            List<SysAclModule> aclModuleList = sysAclModuleMapper.getChildAclModuleListByLevel(before.getLevel());
            if (CollectionUtils.isNotEmpty(aclModuleList))
            {
                for (SysAclModule aclModuleChild : aclModuleList)
                {
                    String Childlevel = aclModuleChild.getLevel();
                    if (Childlevel.indexOf(oldLevel) == 0)
                    {
                        Childlevel = newLevel + Childlevel.substring(oldLevel.length());
                        aclModuleChild.setLevel(Childlevel);
                    }
                }
                sysAclModuleMapper.batchUpdateLevel(aclModuleList);
            }
        }
        sysAclModuleMapper.updateByPrimaryKey(after);
    }

    private boolean checkExist(Integer parentId, String aclModuleName, Integer deptId)
    {
        return sysAclModuleMapper.countByNameAndParentId(parentId, aclModuleName, deptId) > 0;
    }

    private String getLevel(Integer aclModuleId)
    {
        SysAclModule aclModule = sysAclModuleMapper.selectByPrimaryKey(aclModuleId);
        if (aclModule == null)
        {
            return null;
        }
        return aclModule.getLevel();
    }

}
